import { omit } from "@/utils/_";
import Lottie, { AnimationEventCallback, RendererType } from "lottie-web";
import { useEffect, useRef } from "react";

interface Props extends Partial<(typeof Lottie.loadAnimation)["arguments"]> {
  width?: string;
  height?: string;
  stopFrame?: number;
}

export default function LottieView(props: Props) {
  const lottieRef = useRef<any>(null);
  const lottieProps = omit(props, ["width", "height", "stopFrame"]);

  useEffect(() => {
    const config = Object.assign(
      {
        container: lottieRef.current as Element,
        renderer: "svg" as RendererType,
        autoplay: true,
      },
      lottieProps
    );

    const ani = Lottie.loadAnimation(config);
    let listener: null | AnimationEventCallback = () => {
      ani.goToAndStop(ani.totalFrames - (props.stopFrame || 1), true); // 停留在最后一帧
    };
    if (!config.loop) {
      ani.addEventListener("complete", listener);
    }

    return () => {
      if (!config.loop) {
        ani.removeEventListener("complete", listener as AnimationEventCallback);
        listener = null;
      }
      ani.destroy();
    };
  }, [lottieProps]);

  return (
    <div
      style={{ width: props.width, height: props.height }}
      ref={lottieRef}
    ></div>
  );
}
